﻿using System.Linq;
using Microsoft.SharePoint;
using Trentacular.SharePoint.Deployment.Model;
using Trentacular.SharePoint.Deployment.Util;

namespace Trentacular.SharePoint.Deployment.Data.Proxy
{
    public class SiteFeaturesLazyInitializer : BaseDomainListLazyInitializer<Site, SiteFeature>
    {
        protected override object InitializeTarget()
        {
            using (var spSite = new SPSite(Owner.Id))
            {
                var activatedFeatures = spSite.Features
                        .Cast<SPFeature>()
                        .Select(f => f.DefinitionId);

                return Owner.WebApplication.AvailableFeatureDefinitions
                    .Where(fd => fd.Scope == SPFeatureScope.Site)
                    .Select(fd => new SiteFeature
                        {
                            Definition = fd,
                            Parent = Owner,
                            Activated = activatedFeatures.Contains(fd.Id)
                        })
                    .ToVirtualList();
            }
        }
    }
}
